"""
LLM统计模块

负责LLM请求统计和性能监控。
"""

from typing import List
from dataclasses import dataclass


@dataclass
class LLMRequestStats:
    """LLM请求统计数据类"""

    total_requests: int = 0
    successful_requests: int = 0
    failed_requests: int = 0
    total_response_time: float = 0.0
    total_tokens_used: int = 0
    average_response_time: float = 0.0
    error_messages: List[str] = None

    def __post_init__(self):
        if self.error_messages is None:
            self.error_messages = []

    def update_success(self, response_time: float, prompt_tokens: int, response_tokens: int):
        """更新成功请求统计"""
        self.total_requests += 1
        self.successful_requests += 1
        self.total_response_time += response_time
        self.total_tokens_used += prompt_tokens + response_tokens
        self.average_response_time = self.total_response_time / self.successful_requests

    def update_failure(self, error_message: str):
        """更新失败请求统计"""
        self.total_requests += 1
        self.failed_requests += 1
        self.error_messages.append(error_message)

    def get_success_rate(self) -> float:
        """获取成功率"""
        if self.total_requests == 0:
            return 0.0
        return (self.successful_requests / self.total_requests) * 100

    def reset(self):
        """重置统计信息"""
        self.total_requests = 0
        self.successful_requests = 0
        self.failed_requests = 0
        self.total_response_time = 0.0
        self.total_tokens_used = 0
        self.average_response_time = 0.0
        self.error_messages.clear()

    def get_recent_errors(self, count: int = 10) -> List[str]:
        """获取最近的错误信息"""
        return self.error_messages[-count:]

    def __str__(self) -> str:
        """返回统计信息的字符串表示"""
        return f"""
LLM请求统计:
- 总请求数: {self.total_requests}
- 成功请求: {self.successful_requests}
- 失败请求: {self.failed_requests}
- 成功率: {self.get_success_rate():.1f}%
- 平均响应时间: {self.average_response_time:.3f}秒
- 总Token数: {self.total_tokens_used}
        """.strip()